package com.lw.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.commonutil.result.Result;
import com.lw.commonutil.utils.JwtUtils;
import com.lw.order.entity.MemberCourse;
import com.lw.order.entity.Order;
import com.lw.order.mapper.MemberCourseMapper;
import com.lw.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberCourseMapper memberCourseMapper;
    //生成订单
    @PostMapping("/auth/createOrder/{courseId}")
    public Result saveOrder(@PathVariable String courseId,
                            HttpServletRequest request){
        //创建订单，返回订单号
        String orderNo = orderService.createOrder(courseId, JwtUtils.getMemberIdByJwtToken( request ) );
        return Result.ok( orderNo );
    }

    //根据订单id查询订单信息
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq( "order_no",orderId );
        Order order = orderService.getOne( wrapper );
        return Result.ok( order );
    }
    //判断用户购买课程接口
    @GetMapping("/auth/isBuy/{courseId}")
    public Result isBuy(@PathVariable String courseId,
                        HttpServletRequest request){
        //获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken( request );
        QueryWrapper<MemberCourse> wrapper = new QueryWrapper<>();
        wrapper.eq( "member_id",memberId );
        wrapper.eq( "course_id",courseId );
        int count = memberCourseMapper.selectCount( wrapper );
        if (count>0){ //该用户已购买
            return Result.ok( true );
        }else {
            return Result.ok( false );
        }
    }
    //rpc判断用户是否购买课程
    @GetMapping("/inner/isBuy/{memberId}/{courseId}")
    public boolean isBuy(@PathVariable String memberId,
                         @PathVariable String courseId){
        QueryWrapper<MemberCourse> wrapper = new QueryWrapper<>();
        wrapper.eq( "member_id",memberId );
        wrapper.eq( "course_id",courseId );
        int count = memberCourseMapper.selectCount( wrapper );
        if (count>0){ //该用户已购买
            return true ;
        }else {
            return false ;
        }
    }
}
